package edu.ncsu.csc.ip.routing.dv.udp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import edu.ncsu.csc.ip.routing.dv.Node;
import edu.ncsu.csc.ip.routing.dv.RouteEntity;

/**
 * Class <code>distance_vector_udp_local</code>
 * 
 * distance_vector_udp_local to test remote dv on the local machine
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class distance_vector_udp_local {

	public static void main(String[] args) throws Exception {

		distance_vector_udp_local dv = new distance_vector_udp_local();
		RouterRemote r1 = dv.loadRouter("127.0.0.1:65421",
				"./network/node1.txt");
		RouterRemote r2 = dv.loadRouter("127.0.0.1:65422",
				"./network/node2.txt");
		RouterRemote r3 = dv.loadRouter("127.0.0.1:65423",
				"./network/node3.txt");
		RouterRemote r4 = dv.loadRouter("127.0.0.1:65424",
				"./network/node4.txt");
		RouterRemote r5 = dv.loadRouter("127.0.0.1:65425",
				"./network/node5.txt");

		r1.initialize();
		r2.initialize();
		r3.initialize();
		r4.initialize();
		r5.initialize();

		r1.start();
		r2.start();
		r3.start();
		r4.start();
		r5.start();

		System.out.println(" Waiting for network to converge.\n\n");
		Thread.sleep(5000);

		r1.localNode.printRoutingTable();
		r2.localNode.printRoutingTable();
		r3.localNode.printRoutingTable();
		r4.localNode.printRoutingTable();
		r5.localNode.printRoutingTable();

	}

	public RouterRemote loadRouter(String name, String fileName)
			throws IOException {

		RouterRemote router = new RouterRemote(new Node(name),
				Integer.parseInt(name.split(RouterRemote.IP_PORT_DELIM)[1]));

		File file;
		BufferedReader fileReader;
		file = new File(fileName);
		fileReader = new BufferedReader(new FileReader(file));
		String line;
		while ((line = fileReader.readLine()) != null) {
			String[] params = line.split(" ");
			double weight = Double.parseDouble(params[1]);
			Node neighbor = new Node(params[0]);
			router.localNode.neighborsMap.put(neighbor, new RouteEntity(
					neighbor, weight));
		}
		System.out.println("Neighbors Loaded For: " + name);
		fileReader.close();

		return router;
	}

}
